package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.ProductFeign;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;
import java.util.Set;

/**

 * 用于处理用户缓存的定时任务
 * 为了保证Redis中的内存的有效使用。
 * 我们默认保留7天内的用户缓存数据，每天凌晨的时候会把7天前的用户登录缓存数据删除掉
 */
@Component
@Setter@Getter
/* 每次读取重新从nacos获取 */
@RefreshScope
@Slf4j
public class SeckillProductInitJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Value("${sharding.parameters.initSeckillProduct}")
    private String shardingParam;
    @Value("${sharding.count.initSeckillProduct}")
    private Integer count;
    @Autowired
    private ProductFeign productFeign;


    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void execute(ShardingContext ctx) {
        doWork(ctx.getShardingParameter());
    }

    private void doWork(String shardingParameter) {
        log.info("-------------------执行秒杀商品任务-开始-------------------------");
        Result<List<SeckillProductVo>> result = productFeign.selectByTime(Integer.valueOf(shardingParameter));
        if(result.hasError()) {
            log.info("【定时任务】初始化秒杀商品，远程获取商品信息出错"+ JSON.toJSONString(result));
            return;
        }
        List<SeckillProductVo> vos = result.getData();
        for (SeckillProductVo seckillProductVo : vos) {
            redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(shardingParameter),
                    seckillProductVo.getId()+"",
                    JSON.toJSONString(seckillProductVo)
            );
            redisTemplate.opsForHash().put(
                    JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(shardingParameter),
                    seckillProductVo.getId()+"",
                    seckillProductVo.getStockCount()+""
                    );

        }


        log.info("-------------------执行秒杀商品任务-结束-------------------------");

    }


}
